<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/5/31
 * Time: 10:14
 * 资金
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\AppConfig;
use app\common\model\FundsRecord;
use app\common\model\RebateRecord;
use app\common\model\Withdraw;
use app\common\model\WithdrawAccount;
use think\Db;
use think\Exception;

class Funds extends Api{
	protected $noNeedRight = ['*'];
	
	
	/**
	 * 我的资金
	 * @param token 用户token
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function index(){
		$userId = $this->auth->id;
		
		$user = Db::name('user')->field('id, integral, balance, phone_balance, voucher_balance')->find($userId);

		$model = new FundsRecord();
		$funds_type = [];
		foreach($model::$_account_type as $k => $v){
			$funds_type[] = [
				'type' => $k,
				'name' => $v,
				'input' => $k==1?1:0, //余额才允许自己输数量充值
			];
		}
		$user['recharge_type'] = $funds_type;
		
		//提现统计
		$user['withdraw_count'] = Db::name('withdraw')
			->where(['user_id' => $userId, 'status' => Withdraw::STATUS_Y])
			->sum('amount');
		
		$fundsModel = new FundsRecord();
		//累计收益
		$user['earnings_count'] = $fundsModel
			->where(['user_id' => $userId, 'type' => ['in', [$fundsModel::TYPE_REBATE, $fundsModel::TYPE_VOUCHER_REBATE]]])
			->sum('amount');
		
		//待返利
		$user['wait_rebate'] = Db::name('rebateRecord')
			->where(['user_id' => $userId, 'status' => RebateRecord::STATUS_W])
			->sum('amount');
		
		$this->success('查询成功', $user);
	}
	
	
	/**
	 * 查询资金类型及帐单类型
	 */
	public function getTypeList(){
		$model = new FundsRecord();
		
		$accountType = $model::$_account_type;
		foreach($accountType as $k => $v) {
			$returnData['account_type'][] = [
				'type_id' => $k,
				'type_name' => $v
			];
		}
		
		$typeList = $model::$_type;
		foreach ($typeList as $k => $v) {
			$returnData['type_list'][] = [
				'type_id' => $k,
				'type_name' => $v
			];
		}
		
		$this->success('查询成功', $returnData);
	}
	
	/**
	 * 帐单明细
	 * @param token 用户token
	 * @param account_type 资金类型
	 * @param page 分页
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function detail(){
		$userId = $this->auth->id;
		$where['user_id'] = $userId;
		
		$accountType = input('post.type');
		$accountType && $where['account_type'] = $accountType;
		
		$page = input('post.page', 1, 'int');
		
		$type = input('post.operation_type');
		$type && $where['type'] = $type;
		
		$model = new FundsRecord();
		$type = $model::$_type;
		$accType  = $model::$_account_type;
		
		$list = Db::name('fundsRecord')
			->where($where)
			->order(['create_time' => 'desc'])
			->page($page, 20)
			->select();
		
		if($list) {
			foreach($list as $k => $v) {
				$v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
				$v['type'] = $type[$v['type']];
				$v['account_type'] = isset($accType[$v['account_type']]) ? $accType[$v['account_type']] : $v['account_type'];
				$list[$k] = $v;
			}
		}
		
		$this->success('查询成功', $list);
	}
	
	
	/**
	 * 转帐
	 * @param token 用户token
	 * @param phone 对方手机号
	 * @param amount 转帐金额
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function transfer(){
		$userId = $this->auth->id;
		$phone = input('post.phone');
		!$phone && $this->error('对方手机号不能为空');
		
		$preg = '/^1\d{10}$/';
		if(!preg_match($preg, $phone)) {
			$this->error('手机号码格式不正确');
		}
		
		$amount = input('post.amount', 0, 'float');
		if(!$amount || $amount <= 0) {
			$this->error('转帐金额不能为空');
		}
		
		$targetUser = Db::name('user')->where(['mobile' => $phone])->find();
		!$targetUser && $this->error('该手机号没有对应用户');
		
		if($targetUser['id'] == $userId) {
			$this->error('你是不是太闲了，给自己转帐');
		}
		
		$user = Db::name('user')->find($userId);
		if($user['balance'] < $amount) {
			$this->error('余额不足');
		}
		
		Db::startTrans();
		try {
			
			//自己减余额
			$userRes = Db::name('user')->where(['id' => $userId])->setDec('balance', $amount);
			if(!$userRes){
				throw new Exception('扣除金额出错');
			}
			
			//对方加钱
			$targetRes = Db::name('user')->where(['id' => $targetUser['id']])->setInc('balance', $amount);
			if(!$targetRes) {
				throw new Exception('添加金额出错');
			}
			
			
			$logModel = new FundsRecord();
			//自己添加资金记录
			$userLogRes = $logModel->addRecord($userId, $amount,$user['balance'],$logModel::ACCOUNT_TYPE_BALANCE, $logModel::OPE_TYPE_LESS, $logModel::TYPE_TRANSFER, '', '给'.$phone.'转帐', $targetUser['id']);
			if(!$userLogRes){
				throw new Exception('添加扣除资金记录出错');
			}
			
			//对方添加资金记录
			$targetLogRes = $logModel->addRecord($targetUser['id'], $amount, $targetUser['balance'], $logModel::ACCOUNT_TYPE_BALANCE, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_TRANSFER, '', $user['mobile'].'给你转帐', $userId);
			if(!$targetLogRes){
				throw new Exception('添加资金记录出错');
			}
			
			Db::commit();
			$this->success('转帐成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		
	}
	
	
	/**
	 * 我的提现帐号
	 * @param token 用户token
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function account(){
		$id = $this->auth->id;
		
		$rows = Db::name('withdrawAccount')->alias('a')
			->join('bank b', 'a.bank_id = b.id', 'left')
			->where(['a.user_id' => $id, 'a.status' => 1])
			->field('a.id, a.account_no, a.account_name, b.name, b.logo_image')
			->order(['a.create_time' => 'desc'])
			->select();
		$this->success('查询成功', $rows);
	}
	
	
	/**
	 * @param token 用户token
	 * @param bank_id 收款帐号类型ID
	 * @param account_no 收款帐号
	 * @param account_name 收款人
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function addAccount(){
		$userId = $this->auth->id;
		$bankId = input('post.bank_id','', 'int');
		$accountNo = input('post.account_no');
		$accountName = input('post.account_name');
		
		if(!$bankId || !$accountNo || !$accountName) {
			$this->error('参数错误');
		}
		
		$bank = Db::name('bank')->find($bankId);
		if(!$bank){
			$this->error('收款帐号类型不存在');
		}
		
		$model = new WithdrawAccount();
		$res = $model->isUpdate(false)->save([
			'user_id' => $userId,
			'bank_id' => $bankId,
			'account_no' => $accountNo,
			'account_name' => $accountName,
		]);
		
		if($res) {
			$this->success('添加成功');
		} else{
			$this->error('添加出错，请稍候重试');
		}
	}
	
	
	/**
	 * 删除收款帐号
	 * @param token 用户token
	 * @param id 收款帐号ID
	 */
	public function delAccount(){
		$userId = $this->auth->id;
		$id = input('post.id', '', 'int');
		
		$model = new WithdrawAccount();
		$res = $model->save(['status' => $model::STATYS_N],['user_id' => $userId, 'id' => $id]);
		if($res !== false) {
			$this->success('删除成功');
		}
		
		$this->error('删除出错，请稍候重试');
	}
	
	
	/**
	 * 银行列表
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function banks(){
		$banks = Db::name('bank')
			->where(['status' => 1])
			->field('id, name, logo_image')
			->order(['sort' => 'ASC'])
			->select();
		$this->success('查询成功', $banks);
	}
	
	/**
	 * 申请提现
	 * @param token 用户token
	 * @param amount 提现金额
	 * @param account_id 提现帐号ID
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function withdraw(){
		$userId = $this->auth->id;
		$amount = input('post.amount',0, 'float');
		$accountId = input('post.account_id', '', 'int');
		
		!$amount && $this->error('请填写提现金额');
		!$accountId && $this->error('请选择提现帐号');
		
		$user = Db::name('user')->alias('u')
			->join('userVerified v', 'u.id = v.user_id', 'left')
			->where(['u.id' => $userId])
			->field('u.*, v.status as verified_status')
			->find($userId);
		if($user['verified_status'] != 2) {
			$this->error('您还没有实名认证,不能提现');
		}
		
		//查找提现规则
		$rule = Db::name('withdrawRule')
			->find();
		
		$fees = 0;
		if($rule) {
			if($amount < $rule['min_amount']) {
				$this->error('最低提现'.$rule['min_amount'].'元');
			}
			
			if($amount > $rule['one_max_amount']) {
				$this->error('单笔最高提现'.$rule['one_max_amount'].'元');
			}
			
			$where['user_id'] = $userId;
			$where['status'] = ['neq', 2];
			//全部已提现金额
			$allAmount = Db::name('withdraw')->where($where)->sum('amount');
			
			$where['create_time'] = ['egt', strtotime(date('Y-m-d 00:00:00'))];
			
			//当天已提现次数
			$dayNumber = Db::name('withdraw')->where($where)->count();
			//当天已提现金额
			$dayAmount = Db::name('withdraw')->where($where)->sum('amount');
			if($dayNumber >= $rule['number']) {
				$this->error('每天只能申请提现'.$rule['number'].'次');
			}
			
			if($dayAmount+$amount >= $rule['max_amount']) {
				$this->error('每天最高申请提现'.$rule['max_amount'].'元');
			}
			
			if($rule['is_multiple'] && ($amount%$rule['min_amount'] != 0)){
				$this->error('提现金额为'.$rule['min_amount'].'的倍数');
			}
			
			//如果已提现金额加现在提现金额大于免费额度，超出部分计算手续费
			if(($allAmount+$amount) > $rule['free_amount']) {
				if($allAmount >= $rule['free_amount']) {
					$fees = $amount*$rule['ratio'];
				} else {
					$fees = ($allAmount+$amount-$rule['free_amount'])*$rule['ratio'];
				}
			}
			
		}
		
		
		if($amount > $user['balance']){
			$this->error('余额不足');
		}
		
		$account = Db::name('withdrawAccount')->alias('w')
			->join('bank b', 'w.bank_id = b.id', 'left')
			->field('w.account_name, w.account_no, b.name')
			->where(['w.id' => $accountId, 'w.user_id' => $userId, 'w.status' => 1])
			->find();
		if(!$account) {
			$this->error('提现帐号不存在');
		}
		
		Db::startTrans();
		try {
			
			//减余额
			$userRes = Db::name('user')->where(['id' => $userId])->setDec('balance', $amount);
			if(!$userRes) {
				throw new Exception('扣除余额出错');
			}
			
			//添加资金记录
			$logModel = new FundsRecord();
			$logRes = $logModel->addRecord($userId, $amount, $user['balance'], $logModel::ACCOUNT_TYPE_BALANCE, $logModel::OPE_TYPE_LESS, $logModel::TYPE_WITHDRAW);
			if(!$logRes) {
				throw new Exception('添加资金流水出错');
			}
			
			//添加提现记录
			
			$res = Db::name('withdraw')->insert([
				'user_id' => $userId,
				'amount' => $amount,
                'fees' => $fees,
                'real_amount' => $amount-$fees,
                'create_time' => time(),
                'update_time' => time(),
                'account_type' => $account['name'],
                'account_no' => $account['account_no'],
				'account_name' => $account['account_name'],
			]);
			if(!$res) {
				throw new Exception('添加提现记录出错');
			}
			
			Db::commit();
			$this->success('申请成功，等待审核');
		
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	
	
	/**
	 * 提现记录
	 * @param token
	 * @param page
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function withdrawRecord(){
		$userId = $this->auth->id;
		$page = input('post.page', 1, 'int');
		
		$rows = Db::name('withdraw')
			->where(['user_id' => $userId])
			->page($page, 30)
			->order(['create_time' => 'desc'])
			->select();
		if($rows) {
			$status = Withdraw::$_status;
			foreach ($rows as $k => $row) {
				$row['create_time'] = date('Y-m-d', $row['create_time']);
				$row['handle_time'] = $row['handle_time']?date('Y-m-d', $row['handle_time']):'';
				$row['status_text'] = $status[$row['status']];
				$rows[$k] = $row;
			}
		}
		
		$this->success('查询成功', $rows);
	}
	
	/**
	 * 提现规则
	 */
	public function withdrawRule(){
		//查找提现规则
		$rule = Db::name('withdrawRule')
			->find();
		$model = new \app\admin\model\User();
		$rule['userinfo'] = $model->getRelationInfo($this->auth->id);
		$this->success('查询成功', $rule);
	}
	
	/**
	 * 获取返利类型及状态
	 */
	public function getRebateTyep(){
		$model = new RebateRecord();
		$statusList = $model->getStatusList();
		foreach ($statusList as $k => $v) {
			$returnData['status_list'][] = [
				'type_id' => $k,
				'type_name' => $v
			];
		}
		
		$typeList = $model::$typeList;
		foreach($typeList as $k => $v) {
			$returnData['type_list'][] = [
				'type_id' => $k,
				'type_name' => $v
			];
		}
		
		$this->success('查询成功', $returnData);
	}
	
	/**
	 * 返利明细
	 */
	public function rebateRecord(){
		$userId = $this->auth->id;
		$where['user_id'] = $userId;
		$page = input('post.page', 1, 'intval');
		
		$type = input('post.type');
		$type && $where['type'] = $type;
		
		$status = input('post.status');
		$status !== '' && $where['status'] = $status;
		
		$list = Db::name('rebateRecord')
			->where($where)
			->page($page, 20)
			->select();
		
		$statusList = RebateRecord::$_status;
		$typeList = RebateRecord::$typeList;
		if($list) {
			foreach($list as $k => $v) {
				$v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
				$v['type_text'] = $typeList[$v['type']];
				$v['status_text'] = isset($statusList[$v['status']]) ? $statusList[$v['status']] : '';
				$list[$k] = $v;
			}
		}
		
		$this->success('查询成功', $list);
	}
}
